package jp.idahopotato.service;

import java.util.Timer;
import java.util.TimerTask;

import jp.idahopotato.activity.CreateProductHelper;
import jp.idahopotato.aidl.ResultListAIDL;
import jp.idahopotato.aidl.SearchServiceAIDL;
import jp.idahopotato.bean.Result;
import jp.idahopotato.util.Util;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

public class SearchService extends Service {
	private Timer timer = null;
//	private int countTime;
	private static final String FILE_NAME_SKILL = "PreferenceSkillSetFile";
//	private static final String FILE_NAME_OMAMORI = "PreferenceOmamoriSetFile";
	private static final String FILE_NAME_TYPE = "PreferenceTypeSetFile";
	private final RemoteCallbackList<ResultListAIDL> callbacklist = new RemoteCallbackList<ResultListAIDL>();
	private SearchServiceAIDL.Stub serviceCallbackIf = new SearchServiceAIDL.Stub() {

		public void unregisterCallback(ResultListAIDL callback) throws RemoteException {
			callbacklist.unregister(callback);
		}

		public void registerCallback(ResultListAIDL callback) throws RemoteException {
			callbacklist.register(callback);
		}
	};

	private TimerTask task = new TimerTask() {
		@Override
		public void run() {
			int n = callbacklist.beginBroadcast();

			final SharedPreferences skills = getSharedPreferences(FILE_NAME_SKILL, MODE_PRIVATE);
			final SharedPreferences types = getSharedPreferences(FILE_NAME_TYPE, MODE_PRIVATE);
//			final SharedPreferences pref = getSharedPreferences(FILE_NAME_OMAMORI, MODE_PRIVATE);
			CreateProductHelper helper = new CreateProductHelper(SearchService.this);
			SQLiteDatabase db = helper.getReadableDatabase();

			//プリファレンスのロード
			String skillCond = skills.getString("skillSet", "");
			String type = types.getString("type", "ガンナー");
			String gender = types.getString("gender", "男性");
//			int wep = types.getInt("wep", 0);
			int lower = types.getInt("lower", 1);
			int upper = types.getInt("upper", 7);
//			int o_wep = pref.getInt("o_wep", 0);
//			String skill_1 = pref.getString("skill_1", "-1,0");
//			String skill_2 = pref.getString("skill_2", "-1,0");
			int count = 0;
			String skillSet[] = skillCond.split(",");
			String partSet[] = {"頭", "胴", "腕", "腰", "脚"};


			String columns[] = {"t_protec.protec_id", "t_protec.slot"};
			Cursor cursor[] = new Cursor[5];

			SQLiteQueryBuilder build = new SQLiteQueryBuilder();
			build.setTables(" t_protec left join s_to_p on t_protec.protec_id = s_to_p.protec_id left join t_on_skill on s_to_p.skill_id = t_on_skill.skill_id ");
			//検索条件はハンタータイプ、性別、レア度、発動スキルID
			String where = Util.getWhere(type, gender, lower, upper, skillSet);
			for(int j=0; j<partSet.length; j++) {
				String[] param = {partSet[j]};
				String sql = build.buildQuery(columns, where, param, " t_protec.protec_id, t_protec.slot ", null, " sum(s_to_p.skill_point)+t_protec.slot desc ", null);
				cursor[j] = db.rawQuery(sql, param);
			}

			for(int i=0; i<n; i++){
				try{
					cursor[0].moveToFirst();
					for(int a=0; a<cursor[0].getCount(); a++) {
						cursor[1].moveToFirst();
						for(int b=0; b<cursor[1].getCount(); b++) {
							cursor[2].moveToFirst();
							for(int c=0; c<cursor[2].getCount(); c++) {
								cursor[3].moveToFirst();
								for(int d=0; d<cursor[3].getCount(); d++) {
									cursor[4].moveToFirst();
									for(int e=0; e<cursor[4].getCount(); e++) {
										Result rs = new Result();
										rs.setResultName("結果：" + count);
										rs.setHead(cursor[0].getString(0));
										rs.setBody(cursor[1].getString(0));
										rs.setArm(cursor[2].getString(0));
										rs.setWest(cursor[3].getString(0));
										rs.setLeg(cursor[4].getString(0));
										callbacklist.getBroadcastItem(i).addResult(rs);
										Log.d("結果", " "+count + " :" + i);
										count++;
										if(count > 100){
											db.close();
											callbacklist.finishBroadcast();
											return;
										}
										cursor[4].moveToNext();
									}
									cursor[3].moveToNext();
								}
								cursor[2].moveToNext();
							}
							cursor[1].moveToNext();
						}
						cursor[0].moveToNext();
					}

				} catch(RemoteException e){
					Log.e("ERROR", e.toString());
				} catch(Exception e){
					Log.e("ERROR", e.getMessage());
				}
				db.close();
			}
			callbacklist.finishBroadcast();
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		if(SearchServiceAIDL.class.getName().equals(intent.getAction())){
			return serviceCallbackIf;
		}
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		timer = new Timer();
//		countTime = 0;

		timer.schedule(task, 1000);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		timer.cancel();
		timer.purge();
		return super.onUnbind(intent);
	}

}
